package controller;

import entity.StackUser;
import java.io.Serializable;

import javax.ejb.EJB;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import sessionbean.UserFacade;

@ManagedBean(name = "loginBacking")
@SessionScoped
public class LoginBacking implements Serializable {

    private StackUser user;
    private String email;
    
    @EJB
    UserFacade userBean;

    public void login() {
        try {
            System.out.println("logging in: " + email);
            FacesContext facesContext = FacesContext.getCurrentInstance();
            user = userBean.getUserByEmail(email);
            if (user != null) {
                facesContext.getExternalContext().getSessionMap().put("user", user);
                RequestContext context = RequestContext.getCurrentInstance();
                context.addCallbackParam("loggedIn", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public StackUser getUser() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return (StackUser)facesContext.getExternalContext().getSessionMap().get("user");
    }

    public void setUser(StackUser user) {
        this.user = user;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
   
    public boolean isUserLoggedIn(){
        return getUser()!=null;
    }
    
     public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index?faces-redirect=true";
    }
}
